/**
 * Created by Administrator on 2015/6/5.
 */
/**
 * Created by Administrator on 2015/6/5.
 */
var fs=require('fs');
var EventEmiter=require('events').EventEmitter;
var util=require('util');
var RETURN=0x0d; //ascii \r  将光标移动到换行的起始位置 0d=13 回车 return
var NEWLINE=0x0a;// ascii \n  换行 a=10;移动换行至下一行的起始位置
function LineReader(path){
    //_rs就是流
    //this._rs=fs.createReadStream(path,'r');
    this.filePath = path;
    this.bin = fs.readFileSync(path);

    if (this.bin[0] === 0xEF && this.bin[1] === 0xBB &&this.bin[2] === 0xBF) {
        this.bin =this.bin.slice(3);
    }

    //return this.bin.toString('utf-8');
}
//EventEmiter可以注册监听，发射事件
util.inherits(LineReader,EventEmiter);
//原型上的newListener方法注册了监听，监听的触发时机是当对象上注册了监听事件时触发。例如下面的newLine和end方法。
LineReader.prototype.on('newListener',function(ev,fn){
    if(ev=='newLine'){
        var self=this;
        var line=[];
        //this.bin.on('readable',function(){

        fs.open(this.filePath,'r',function(err,fd){
                fs.read(fd,this.bin,0,1,null,function(err,bytesRead,buffer){
                    //console.log(buff.toString());

                    var ch;
                    //while(null!=(ch=this.read(1))){
                    while(null!=(ch=bytesRead)){
                        if(ch[0]==RETURN){
                            this.read(1);
                            self.emit('newLine',Buffer.concat(line).toString());
                            line=[];
                        }else{
                            line.push(ch);
                        }
                    }

                });
        });

        //});
/*        this.bin.on('end',function(){
            self.emit('newLine',Buffer.concat(line).toString());
            self.emit('end');
        });*/
    }
});

var reader=new LineReader('./1.txt');
console.log("123 "+reader);

reader.on('newLine',function(data){
    console.log(data);
});
reader.on('end',function(){
    console.log('end');
});













